﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Windows.Forms;
using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.Geodatabase;


namespace BesAsm.Emgaats.Maintenance
{
    public class UIAppendLinksButton : ESRI.ArcGIS.Desktop.AddIns.Button
    {
        private ApplicationWindow _appWindow;

        public UIAppendLinksButton()
        {
            _appWindow = new ApplicationWindow(ArcMap.Application.hWnd);
        }

        protected override void OnClick()
        {
            System.Windows.Forms.Cursor.Current = Cursors.WaitCursor;
            try
            {
                Configuration config = EmgaatsMaintenanceExtension.Extension.Configuration;
                IFeatureClass dmeClass = config.DmeLinksClass;
                IFeatureLayer[] dmeLayers = EmgaatsMaintenanceExtension.Extension.FindFeatureLayers(dmeClass);

                int selectionCount = 0;
                foreach (IFeatureLayer dmeLayer in dmeLayers)
                {
                    IFeatureSelection selection = dmeLayer as IFeatureSelection;
                    {
                        if (selection != null)
                            selectionCount += selection.SelectionSet.Count;
                    }
                }

                if (selectionCount > 0)
                {
                    IActiveView activeView = ArcMap.Document.FocusMap as IActiveView;
                    FieldMapping fieldMapping = config.LinkFieldMapping;

                    IFeatureClass appendClass = EmgaatsMaintenanceExtension.Extension.Settings.AppendClass;
                    IFeatureLayer appendLayer = EmgaatsMaintenanceExtension.Extension.FindFeatureLayer(appendClass);
                    if (appendLayer != null)
                        appendLayer.Cached = true;

                    try
                    {
                        IFeatureCursor cursor = appendClass.Insert(false);
                        IFeatureBuffer buffer = appendClass.CreateFeatureBuffer();
                        try
                        {
                            foreach (IFeatureLayer dmeLayer in dmeLayers)
                            {
                                IFeatureSelection selection = dmeLayer as IFeatureSelection;
                                if (selection != null && selection.SelectionSet.Count > 0)
                                {
                                    IEnumIDs selectionIds = selection.SelectionSet.IDs;
                                    int selectedId = selectionIds.Next();
                                    while (selectedId > 0)
                                    {
                                        IFeature dmeFeature = dmeClass.GetFeature(selectedId);
                                        try
                                        {
                                            if (dmeFeature != null)
                                            {
                                                buffer.Shape = dmeFeature.ShapeCopy;

                                                // Copy attributes
                                                for (int f = 0; f < buffer.Fields.FieldCount; f++)
                                                {
                                                    IField toField = buffer.Fields.get_Field(f);
                                                    if (toField.Type != esriFieldType.esriFieldTypeOID && toField.Type != esriFieldType.esriFieldTypeGeometry && toField.Editable)
                                                    {
                                                        if (fieldMapping.Contains(toField.Name) && !fieldMapping[toField.Name].Ignore)
                                                        {
                                                            object dbValue = fieldMapping.GetValueForField(toField.Name, dmeFeature);
                                                            if (dbValue != DBNull.Value || toField.IsNullable)
                                                            {
                                                                buffer.set_Value(f, dbValue);
                                                            }
                                                        }
                                                    }
                                                }

                                                cursor.InsertFeature(buffer);
                                            }
                                        }
                                        finally
                                        {
                                            EmgaatsMaintenanceExtension.ReleaseComObject(dmeFeature);
                                        }

                                        selectedId = selectionIds.Next();
                                    }
                                    cursor.Flush();
                                }
                            }
                        }
                        finally
                        {
                            EmgaatsMaintenanceExtension.ReleaseComObject(cursor);
                        }

                    }
                    finally
                    {
                        if (appendLayer != null)
                        {
                            activeView.PartialRefresh(esriViewDrawPhase.esriViewGeography, appendLayer, null);
                            appendLayer.Cached = false;
                        }
                    }
                }
                else
                {
                    MessageBox.Show(_appWindow, "No DME link features are selected.", "No Selection", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            catch (Exception ex)
            {
                string msg = string.Format("An error occured: {0}", ex.Message);
                MessageBox.Show(_appWindow, msg, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                System.Windows.Forms.Cursor.Current = Cursors.Default;
            }
        }

        protected override void OnUpdate()
        {
            bool enabled = false;
            if (ArcMap.Application != null &&
                EmgaatsMaintenanceExtension.Extension != null &&
                EmgaatsMaintenanceExtension.Extension.Settings != null &&
                EmgaatsMaintenanceExtension.Extension.Settings.AppendClass != null &&
                EmgaatsMaintenanceExtension.Extension.DmeSelectionCount > 0)
            {
                enabled = true;
            }

            this.Enabled = enabled;
        }
    }
}
